const commonService = require("../services/common");

exports.getStableAccessToken = async (ctx, next) => {
    const { access_token, expires_in } = await fetch("https://api.weixin.qq.com/cgi-bin/stable_token", {
        method: "POST",
        body: JSON.stringify({
            grant_type: "client_credential",
            appid: "wx39268561e231bae4",
            secret: "8e4d8316313be540059103c28f5c431d",
            force_refresh: false
        })
    }).then((response) => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        return response.json();
    });

    await commonService.getStableAccessToken({ access_token });

    reqHandler(expires_in);
};

function reqHandler(expires_in) {
    setTimeout(() => {
        getStableAccessToken();
    }, expires_in * 1000 - 6 * 60 * 1000);
}
